package com.lz.helper.idcard

import android.content.Context
import android.util.Log
import java.util.concurrent.atomic.AtomicBoolean

//指纹识别
abstract class FingerRequest(
    protected val context: Context,
    protected val matcher: ByteArray,
    protected val threshold: Float,
    protected val handler: FingerHandler
) : Runnable {

    companion object {

        const val TAG = "FingerRequest"

        //打开失败
        const val OPEN_FAIL = 0

        //GetImage失败
        const val ERR_IMAGE = 1

        //未按
        const val ERR_UN_PRESS = 2

        //匹配异常
        const val ERR_MATCHING = 4
    }

    //是否暂停, 暂停时将线程挂起
    private var isPaused = false

    //是否退出
    private var quit = AtomicBoolean(false)

    //线程wait notify
    private var async = Object()

    //暂停
    fun pause() {
        synchronized(async) { isPaused = true }
    }

    //恢复
    fun restart() {
        synchronized(async) { isPaused = false; async.notify() }
    }

    //中断退出
    fun quit() {
        synchronized(async) { quit.set(true); async.notify() }
    }

    //是否退出
    fun isQuit(): Boolean = quit.get()

    //等待处理
    protected fun await() {
        synchronized(async) {
            while (isPaused && !quit.get()) {
                try {
                    Log.d(TAG, "...... FingerRequest wait ......")
                    async.wait()
                    Log.d(TAG, "...... FingerRequest resume  ......")
                } catch (_: InterruptedException) {
                }
            }
        }
    }

    //延时处理
    protected fun delay(time: Long) {
        synchronized(async) {
            if (!isPaused) {
                try {
                    async.wait(time)
                } catch (_: InterruptedException) {
                }
            }
        }
    }

    interface FingerHandler {

        //发送打开成功
        fun sendFingerOpenSuccess()

        //异常状态
        fun sendFingerError(error: Int)

        //发送结果
        fun sendFingerResult(threshold: Int)
    }

    interface Factory {
        fun create(context: Context, matcher: ByteArray, threshold: Float, handler: FingerHandler): FingerRequest
    }
}